//
//  NetWorkHelper.swift
//  WangPu
//
//  Created by xiaozhi on 15/9/22.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit
let baseUrl:String! = "http://appapi.wangpugo.com/mapi"
let payBaseUrl:String! =  "http://appapi.wangpugo.com/"
typealias Task = ((NSData!,NSURLResponse!,NSError!)->Void)?
typealias CommonTask = (()->Void)?
class NetWorkHelper: NSObject {
    let session:NSURLSession = NSURLSession.sharedSession()
//    var compeleteHandle:((NSData!, NSURLResponse!, NSError!) -> Void)?
    class func taskWith(responsSuccedTask:CommonTask,dataAvalid:CommonTask,failedTask:CommonTask)->Task?{
        return nil
    }
    func requestStart(method:String?,parameters:AnyObject?,compeleteHandle:((NSData!, NSURLResponse!, NSError!) -> Void)?){
        if let methodStr = method{
            if let parameterObj: AnyObject = parameters{
                var aError:NSError?
                let bodyData: NSData?
                do {
                    bodyData = try NSJSONSerialization.dataWithJSONObject(parameterObj, options: NSJSONWritingOptions.PrettyPrinted)
                } catch let error as NSError {
                    aError = error
                    bodyData = nil
                }
                if aError != nil || bodyData == nil{
                    print("invalid post data!")
                    return
                }
                var requestUrl = baseUrl+methodStr
                let array = methodStr.componentsSeparatedByString("/")
                if array.count > 3{
                    requestUrl = payBaseUrl+methodStr
                }
                let request = NSMutableURLRequest(URL: NSURL(string:requestUrl)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)
                request.HTTPMethod="POST"
                request.HTTPBody = bodyData
                let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in
                    if error == nil{
                        let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
                        //                            println(string)
                        if method == "/appunionpay/payment/getOrder" {
                            let range = string?.rangeOfString("{")
                            let str = string?.substringFromIndex((range?.location)!)
                            compeleteHandle?(str!.dataUsingEncoding(NSUTF8StringEncoding),response,error)
                            return
                        }
                        compeleteHandle?(string!.dataUsingEncoding(NSUTF8StringEncoding),response,error)
                    }
                    else{
                        compeleteHandle?(data,response,error)
                    }

                })
                task.taskDescription = method
                task.resume()
            }
            
        }
    }
    deinit{
        print("NetWorkHelper deinit")
    }
}
